package cn.stylefeng.guns.sys.modular.auth.controller;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.sys.modular.auth.bean.SysRegisterBean;
import cn.stylefeng.guns.sys.modular.auth.service.AuthService;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class SysRegisterController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysRegisterController.class);

    private final AuthService authService;

    @ApiOperation(value = "发送注册邮件", notes = "发送注册邮件")
    @GetMapping(value = "/verification")
    @ResponseBody
    public ResponseData<?> sendRegisterEmail(@RequestParam("account") String account, @RequestParam("email") String email, @RequestParam("locale") String locale) {
        try {
            return authService.sendRegisterEmail(account, email, locale);
        } catch (Exception e) {
            LOGGER.error("发送注册邮件异常", e);
            if(StrUtil.isNotBlank(locale) && "en".equals(locale)) {
                return ResponseData.error("Operation exception!");
            } else {
                return ResponseData.error("操作异常！");
            }
        }
    }

    @ApiOperation(value = "注册用户", notes = "注册用户")
    @PostMapping(value = "/register")
    @ResponseBody
    public ResponseData<?> doRegister(@RequestBody SysRegisterBean registerBean) {
        try {
            return authService.doRegister(registerBean);
        } catch (Exception e) {
            LOGGER.error("发送注册邮件异常", e);
            if(registerBean != null && "en".equals(registerBean.getLocale())) {
                return ResponseData.error("Operation exception!");
            } else {
                return ResponseData.error("操作异常！");
            }
        }
    }

    @ApiOperation(value = "下载证书", notes = "下载证书")
    @GetMapping(value = "/certificate/download")
    @ResponseBody
    public void downloadCertificate(HttpServletResponse response) {
        try {
            authService.downloadCertificate(response);
        } catch (Exception e) {
            LOGGER.error("下载证书异常", e);
            throw new RuntimeException("下载证书异常");
        }
    }

    @ApiOperation(value = "绑定sn", notes = "绑定sn")
    @PostMapping(value = "/bindSn")
    @ResponseBody
    public ResponseData<?> bindSn(@RequestBody SysRegisterBean registerBean) {
        try {
            return authService.bindSn(registerBean);
        } catch (Exception e) {
            LOGGER.error("绑定序列号异常", e);
            return ResponseData.error("操作异常！"+e.getMessage());
        }
    }
}
